<?php
namespace app\pay\controller\yop;

use think\Controller;
use pay\yop\Config;

use customtool\Utils;
use customtool\Rsa;

class Order extends Controller {
    private $cfg = null;
    
    public function _initialize() {
        $this->cfg = new Config();
    }
    
    /*
     * @params
     * $data    -> post参数
     * $resPayBis     -> model('PayBis')相关参数
     */
    public function index($data, $resPayBis, $resPayPlatform) {
        header("Content-Type: text/html; charset=utf-8");
        $verSign = $data['signature'];
        unset($data['signature']);
        $md5key = $resPayBis->md5key;
        $data['signature'] = payChangyuanSign($data, $md5key); // 创建签名
        // 验证签名
        if($verSign == $data['signature']) {
            // 对数据进行解析，向平台发起请求等
            $res = $this->reqYopData($data, $resPayBis, $resPayPlatform);
            return $res;
        } else {
            // <畅远>签名验证失败
            return changyuanSignFalse();
        } 
    } 

    /*
     * @params
     * $data       -> post参数
     * $resPayBis  -> model('PayBis')相关参数
     */
    private function reqYopData($data, $resPayBis, $resPayPlatform) {
        $postData = $this->packageTransferData($data, $resPayPlatform);
        
        // 使用公钥加密
        $encryptData = Rsa::publicEncrypt($postData);
        

        $sourceData = Utils::curlRetStr($resPayPlatform->server_root . '/Transfer.php', $encryptData);

        // 使用公钥解密
        $decryptData = Rsa::publicDecrypt($sourceData);
        if($decryptData == null) {
            return $sourceData; // 密钥不可用
        }
        
        $resData = json_decode($decryptData, true);
        if($resData['code'] == true) { // 下单成功
            /*
            * 组装保存到数据库的订单信息
            * @params packageOrderData(post参数 易宝订单号 model('PayBis')相关参数 手续费)
            */
            $orderData = $this->packageOrderData($data, $resData['source']['uniqueOrderNo'], $resPayBis);
            // return $orderData;
            $resPayBisOrder = model('PayBisOrder')->get(['mchnt_orderid' => $data['mchnt_orderid']]);
            if($resPayBisOrder) {
                return orderAddFalse();  // 订单号已存在，请勿重复下单
            } else {
                payBisOrderAdd($orderData, $resData['url']); // 将订单信息保存到数据库中
                /*
                 * 订单返回参数
                 * @params payOrderTrue(商户号 商户订单号 商户通知地址 金额 系统单号 支付地址 md5密钥)
                 */
                return payOrderTrue($resPayBis->merchant_id, $data['mchnt_orderid'], $data['pay_callbackurl'], $data['pay_amount'], $resData['source']['uniqueOrderNo'], $resData['url'], $resPayBis->md5key); 
            }     
        } else { // 支付平台内部签名验证失败
            return json_encode($resData, 320);
        } 
    } 
    
    /*
     * 组装保存到数据库的订单信息
     * 
     * @params
     * $data           -> post参数
     * $uniqueOrderNo  -> 系统订单号
     * $resPayBis      -> model('PayBis')相关参数
     */
    private function packageOrderData($data, $uniqueOrderNo, $resPayBis) {
        $orderDataArr = array(
            'pay_orderid'     => $uniqueOrderNo,            // 平台订单号
            'mchnt_orderid'   => $data['mchnt_orderid'],    // 商户订单号
            'merchant_id'     => $resPayBis->merchant_id,   // model('PayBis')中的商户号
            'pay_amount'      => $data['pay_amount'],       // 交易金额
            'pay_tradetype'   => $data['pay_tradetype'],    // 支付通道
            'timeout_express' => $data['timeout_express'],  // 订单有效时长, 默认24小时
            'pay_callbackurl' => $data['pay_callbackurl']   // 异步回调通知地址
        );
        return json_encode($orderDataArr, 320);
    }
        
    /*
     * 组装发给中转服务器的数据
     */
    private function packageTransferData($data, $resPayPlatform) {
        $transferData = array(
            "type"               => 'Yop',
            "group_merchant_id"  => $resPayPlatform->group_merchant_id,
            "parent_merchant_id" => $resPayPlatform->parent_merchant_id,
            "private_key"        => $resPayPlatform->private_key,
            "public_key"         => $resPayPlatform->public_key,
            "callbackurl"        => $resPayPlatform->callbackurl,
            "source"             => $data,
        ); 
        return json_encode($transferData, 320);
    }
}

